#!/usr/bin/env python

"""This script provides a benchmark for the JIT compiler, in
particular the speed of the in-memory cache."""

# Copyright (C) 2008-2010 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2008-09-04
# Last changed: 2010-05-03

from dolfin import *
from time import time

print "JIT compilation (in memory cache)"

# Benchmark parameters
NUM_REPS = 10
SIZE = 3

# Create mesh
mesh = UnitCubeMesh(SIZE, SIZE, SIZE)

# Create form (velocity equation for "G2")
V = VectorFunctionSpace(mesh, "Lagrange", 1)
Q = FunctionSpace(mesh, "Lagrange", 1)
DG = FunctionSpace(mesh, "DG", 0)
DGv = VectorFunctionSpace(mesh, "DG", 0)

v  = TestFunction(V)
q  = TestFunction(Q)
u  = TrialFunction(V)
p  = TrialFunction(Q)
u0 = Function(V)
p1 = Function(Q)
W  = Function(DGv)
nu = Constant(0.1)
k  = Constant(0.1)
h  = CellSize(mesh)
d1 = h
d2 = 2.0*h

U = 0.5*(u0 + u)

F = (1.0/k)*inner(v, u - u0) + inner(v, grad(U)*W) + nu*inner(grad(v), grad(U)) - div(v)*p1 + \
    d1*inner(grad(v)*W, grad(U)*W) + d2*div(v)*div(U)
a = lhs(F*dx)

# JIT compile once
t0 = time()
jit(a)
t1 = time() - t0

# Then JIT compile some more
t0 = time()
for i in range(NUM_REPS):
    jit(a)
t2 = (time() - t0) / float(NUM_REPS)

print "Disk cache:     ", t1
print "In-memory cache:", t2
print "BENCH", t2
